<template>
  <div id="recordid" style="background:rgba(255,255,255,0.3);">
    <h2 style="color: red" v-show="showMsgFlag">{{showMsg}}</h2>
    <span id="spantimeid" style="">请记录昨天账单 {{time}}</span>
    <Rule v-show="show" />
    <div id="showRuleid" > <button style="border-radius: 1px;" @click="showRule"> {{showName}}规则</button> </div><br>
<!--    列出各个app-->
    <div id="appDataref" >
<!--      循环apps-->
    <div  v-for="(item,i) in apps"  v-bind:key="i">
<!--      显示app图标和名称-->
      <h2> <img height="28" width="28" v-bind:src="item.ico" > {{item.name}} </h2>
<!--      显示该app下子账单123.。-->
      <div style="margin-left: 0%; margin-top: -3%">
<!--        各个app-->
        <ul  class="allApps">
          <li  style="margin-bottom: 10px;margin-left: -1%;width: 100%" v-for="(ii,bbb) in item.count" v-bind:key="bbb">
<!--            详情1的单笔金额-->
            <span style="width: 30%" class="subDetail">元<input @change="submitData" type="number"  > </span>
<!--            选择分类-->
            <span style="width: 4px" class="subDetail"> 类<select @change="setSelect2(i,ii-1)">
                                      <option  v-for="(select1) in detailTypes"  v-bind:key="select1">{{select1.type1Name}}</option>
                                    </select>

                                    <select style="width: 60px" @change="submitData" >

                                      <option v-show="true" v-for="(select2) in detailTypes[0].type2Names" v-bind:key="select2" >{{select2}}</option>

                                    </select>


            </span>

<!--            是否分期-->
            <span style="margin-right: 1%" class="subDetail"> 分期<select @change="submitData">
                                          <option selected>0</option>
                                          <option>3</option>
                                          <option>6</option>
                                          <option>12</option>
                                          <option>24</option>
                                    </select> </span>


          </li>
<!--          <button class="button" style="vertical-align:middle"><span>Hover </span></button>-->
        </ul>
          <div style="margin-left: 40%">
            <button class="button" id="delSubid" @click="addDelCount(i,false)">删除</button>
            <button class="button" id="addSubid" @click="addDelCount(i,true)">添加</button>
          </div>

      </div>
    </div>
    </div>

    <p5 v-show="false" id="p5id">{{this.returnData}}</p5>

    <p5  v-show="false"  id="p5id_r1">{{this.r1}}</p5>
    <button v-show="false" id="aaa_id"  @click="aaa">测试</button>
    <input v-show="false"  id="input_id" type="text"  >

    <br>
    <br>
    <hr>
    <br>

  </div>
</template>

<script>
import Rule from "@/components/Rule";
import Vue from "vue";

export default {
  name: "Record",
  components:{
    Rule
  },
  methods:{
    getviewCookie: function (cname) {
      var name = cname + "=";
      var ca = document.cookie.split(';');
      // console.log("获取cookie,现在循环")
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        // console.log(c)
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1){
          return c.substring(name.length, c.length);
        }
      }
      return "";
    },
    getCookie: function (cname) {
      let Base64 = require('js-base64').Base64
      var name = cname + "=";
      var ca = document.cookie.split(';');
      // console.log("获取cookie,现在循环")
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        // console.log(c)
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1){
          return Base64.decode(  c.substring(name.length, c.length));
        }
      }
      return "";
    },
    setSelect2:function (i,ii) {
      let childNode = document.getElementById('appDataref').childNodes[i].childNodes[1].childNodes[0].childNodes[ii].childNodes[1];
      let select1 = childNode.childNodes[1].value;
      let select2 = childNode.childNodes[2];

      // console.log('获取select1和2完成 下面开始打印')
      // console.log(select1)
      // console.log(select2)
      // console.log('打印完成')

      // console.log('下面开始遍历数组寻找对应的key')
      for (let j = 0; j < this.detailTypes.length; j++) {
        let b = this.detailTypes[j].type1Name == select1;
        if (b){
          // console.log('找到了，下面是待添加到select2里面的新数组')
          let type2Names = this.detailTypes[j].type2Names;
          // console.log(type2Names)
          // 这是新的select2
          // // console.log(type2Names)

          // 删除之前select2的子节点
          // console.log('下面开始先倒序删除select2之前的所有子节点，删除')
          for (let k = 0; k < select2.childNodes.length ; k++) {
            select2.removeChild(select2.childNodes[0]);
          }

          for (let k = select2.childNodes.length-1; k > -1 ; k--) {
            select2.removeChild(select2.childNodes[k]);
          }

          // console.log('删除完成，再看一下select2里面的内容')
          // console.log(document.getElementById('appDataref').childNodes[i].childNodes[1].childNodes[0].childNodes[ii].childNodes[1].childNodes[2])

          // console.log('下面开始把新的内容挂上')
          //挂新
          for (let k = 0; k < type2Names.length; k++) {
            var option=document.createElement("option");
            option.innerHTML = type2Names[k];
            select2.appendChild(option);
          }
          // console.log('挂新完成，看一下最终select2内容')
          // console.log(document.getElementById('appDataref').childNodes[i].childNodes[1].childNodes[0].childNodes[ii].childNodes[1].childNodes[2])

          this.submitData()
        }
      }

    },
    addDelCount:function (index,type) {
      if (type) {
        this.apps[index].count = this.apps[index].count + 1;
      }else if (this.apps[index].count > 1){
        this.apps[index].count = this.apps[index].count - 1;
      }else {
        this.showMsg ='已经是最小了，不能再删除了噢';
        this.showMsgFlag = true;
      }
    },
    aaa:function () {

      var p2 = document.getElementById('input_id').value;
      // var p2='yesterday={"time":"2021-11-27","value":1}; ' +
      //     'week={"time":"2021-11-22","value":2}; ' +
      //     'month={"time":"2021-11","value":3}; ' +
      //     'season={"time":"2021-4","value":4}; ' +
      //     'year={"time":2021,"value":5}; ' +
      //     'lately7Day=[{"time":"2021-11-27","value":1},' +
      //     '{"time":"2021-11-26","value":11},' +
      //     '{"time":"2021-11-25","value":111},' +
      //     '{"time":"2021-11-24","value":222},' +
      //     '{"time":"2021-11-23","value":333},' +
      //     '{"time":"2021-11-22","value":444},' +
      //     '{"time":"2021-11-21","value":555}]; ' +
      //     'lately6Month=[{"time":"2021-11","value":980},' +
      //     '{"time":"2021-10","value":776},' +
      //     '{"time":"2021-9","value":567},' +
      //     '{"time":"2021-8","value":534},' +
      //     '{"time":"2021-7","value":876},' +
      //     '{"time":"2021-6","value":1233}]';
      console.info('上次cookie传入')
      console.log(p2)
      //重新设置cookie
      // Vue.prototype.viewCookies1=['yesterday','week','month','season','year' ]
      // Vue.prototype.viewCookies2=[ 'lately7Day', 'lately6Month']

      //te2是把上次的cookie设置到浏览器
      this.te2(p2)

      //这是填写表单后，设置cookie最新
      let viewCookies1 = Vue.prototype.viewCookies1;
      let viewCookies2 = Vue.prototype.viewCookies2;
      for (let i = 0; i < viewCookies1.length; i++) {
        let cookie = JSON.parse(this.getviewCookie(viewCookies1[i]));
        cookie.value= this.yesterdayCount+(cookie.value)*1;
        this.setViewCookie(viewCookies1[i],JSON.stringify(cookie));
      }
      for (let i = 0; i < viewCookies2.length; i++) {
        let cookie = JSON.parse(this.getviewCookie(viewCookies2[i]));
        cookie[0].value =(cookie[0].value)*1+( this.yesterdayCount)*1;
        this.setViewCookie(viewCookies2[i],JSON.stringify(cookie));
      }

      let cookie1 = document.cookie;

      let innerHTML = document.getElementById('p5id').innerHTML;
      // let innerHTML_cs = document.getElementById('p5id_cs').innerHTML;
      // alert(innerHTML) 手机先设置一遍 cookie  然后再加 在传出去
      console.info('本次增量数据')
       console.log(innerHTML)
      console.info('最新cookie')
      console.log(cookie1)
      this.r1 = innerHTML +'🔺' + cookie1;
    },
    showRule:function () {
      this.show = !this.show;
      this.showName = !this.show?'显示':'隐藏';

      //便便设置vconsole显示与否
      document.getElementById('__vconsole').style.visibility= this.show?"visible":"hidden";
    },
    submitData:function (){
      // console.log('')
      // console.log('获取所有app内容')
      let allApp = document.getElementsByClassName('allApps');
      // console.log(allApp)
      // console.log(this.apps)
      let currentReturnList=[];
      this.yesterdayCount=0;

      // console.log('迭代每个app')
      for (let i = 0; i < this.apps.length; i++) {
        var myApp = {id:'',name:'',bills:[]}
        let app = this.apps[i];
        let element = allApp[i].childNodes;
        // console.log('app的id：'+ app.id)
        // console.log('app的名称：'+app.name)
        myApp.id=app.id;
        myApp.name=app.name;
        var bills=[];
        // // console.log(element)
        for (let j = 0; j < element.length; j++) {
          var bill= {money:0,type1:'',type2:'',instalments:''}
          let money = element[j].childNodes[0].childNodes[1].value;
          if(money == "" || money == undefined|| money == 0){
            continue;
          }
          // console.log('app的一个账单金额：'+money)
          bill.money=money;
          this.yesterdayCount = (this.yesterdayCount*1)+(money*1);
          let type1 = element[j].childNodes[1].childNodes[1].value;
          let type2 = element[j].childNodes[1].childNodes[2].value;
          // console.log('app的一个账单类型1：'+type1)
          // console.log('app的一个账单类型2：'+type2)
          bill.type1=type1;
          bill.type2=type2;
          let instalments = element[j].childNodes[2].childNodes[1].value;
          // console.log('app的一个账单的分期数：'+instalments)
          bill.instalments=instalments;
            bills.push(bill);
        }
        myApp.bills=bills;
        if (bills.length > 0){
          currentReturnList.push(myApp)
        }
      }
      this.returnData=[{createDate:this.getYesterday(),user:this.getCookie("familyvuegitee_iphoneName")}];
      this.returnData.push(currentReturnList)
      // console.log('输入最终的returnData')
      // console.log(this.returnData)
    },
    setViewCookie:function (cname,cvalue) {
      // var cname='familyvuegitee_background';
      var exdays=20;
      // cvalue = 'https://cn.bing.com/'+cvalue;
      var d = new Date();
      d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
      var expires = "expires=" + d.toUTCString();
      // console.info(cname + "=" + cvalue + "; " + expires);
      document.cookie = cname + "=" + cvalue + "; " + expires;
      // console.info("设置cookie成功："+document.cookie);
      // alert("设置cookie成功："+cvalue)

    },
    getYesterday:function () {
      var d=new Date();
      var t =d.getTime()-1000*60*60*24;
      var day=new Date(t);
      return day.getFullYear()+'-'+(day.getMonth()+1)+'-'+day.getDate();
    },
    getDate:function (format,type) {
      var d=new Date();
      var t = 0;
      var day = 0;

      if (format=='yesterday') {
          t = d.getTime() - 1000 * 60 * 60 * 24;
          day = new Date(t);
        return( day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate());
      } else if (format == 'week'){
        let day1 = d.getDay();
        day=new Date();
        if (day1 > 1){
          t = d.getTime() - 1000 * 60 * 60 * 24* (day1-1);
          day = new Date(t);
        }else if (day1 === 0){
          t = d.getTime() - 1000 * 60 * 60 * 24* 6;
          day = new Date(t);
        }
        return( day.getFullYear()+'-'+(day.getMonth() + 1)+ '-' + day.getDate() );
      }else if (format=='month'){
        return( d.getFullYear()+'-'+(d.getMonth() + 1) );
      }else if (format=='season'){
        let number = d.getMonth() + 1;
        var s= Math.ceil(number/3);
        return( d.getFullYear()+'-'+ s) ;
      }else if (format=='year'){
        return ( d.getFullYear())
      }else if (type=="day"){
        // format为 -1返回昨天 -2返回前天 -3返回上3天 -4.。。。
        t = d.getTime() + 1000 * 60 * 60 * 24* format;
        day = new Date(t);
        return( day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate());

      }else if (type=="month"){
        // format为 -1返回上月 -2上二个月。。。最多减去12

        let number1 = d.getMonth()+1;
        let number2 = d.getFullYear();

        if (number1+format <1){
          format = (number1+format)
          number2 = --number2;
          return number2+'-'+(12+format);
        }else {
          return number2 + '-' + (number1 + format);
        }
      }


    },
    getListVById:function (list,id) {
      for (let i = 0; i < list.length; i++) {
        let element = list[i];
        if (element.time ==id){
          return element.value;
        }
      }
    },
    te2:function (p1) {
      // console.log(document.cookie);
      var cs=  p1;
      //首先查询有没有cookie 如果没有就设置
      for (let i = 0; i < this.viewCookies1.length; i++) {
        let viewCookie = this.viewCookies1[i]; //获取每个cookieKey
        let cookieV = this.getCookieByString(viewCookie,cs); //获取浏览器存储的cookieValue
        let currentDate = this.getDate(viewCookie);
        if (cookieV == ""){
          //找不到就新建
          this.setViewCookie(viewCookie,JSON.stringify({time: currentDate , value:0}))
        }else {
          //找到了，判断一下是否需要重置
          if (JSON.parse(cookieV).time != currentDate){
            this.setViewCookie(viewCookie,JSON.stringify({time: currentDate , value:0}))
          }else {
            //把cookie同步
            this.setViewCookie(viewCookie,JSON.stringify({time: currentDate , value:JSON.parse(cookieV).value}))
          }
        }
      }

      for (let i = 0; i < this.viewCookies2.length; i++) {
        let viewCookie2 = this.viewCookies2[i]; //获取每个cookieKey
        let cookie2V = this.getCookieByString(viewCookie2,cs); //获取浏览器存储的cookieValue
        var v=[];
        let b = i===0;
        if (b){ //给v赋值前7天
          for (let j = -1; j >=-7 ; j--) {

            v.push({time:this.getDate(j,'day'), value:0})
          }
        }else { //给v赋值前6月
          for (let j = -0; j >=-5 ; j--) {
            v.push({time:this.getDate(j,'month'), value:0})
          }
        }

        if (cookie2V == ""){
          this.setViewCookie(viewCookie2,JSON.stringify(v))
        }else if (b){
          //清空过去数据
          let cookie2Day = JSON.parse(this.getCookieByString(viewCookie2,cs));
          for (let j = 0; j < v.length; j++) {
            let vTime = v[j].time;
            let cValue = this.getListVById(cookie2Day,vTime);
            if (cValue=='' || cValue==undefined){
              cValue = 0;
            }
            v[j].value = cValue;
          }
          this.setViewCookie(viewCookie2,JSON.stringify(v))

        }else {
          //清空过去数据
          let cookie2Month = JSON.parse(this.getCookieByString(viewCookie2,cs));
          for (let j = 0; j < v.length; j++) {
            let vTime = v[j].time;
            let cValue = this.getListVById(cookie2Month,vTime);
            if (cValue=='' || cValue==undefined){
              cValue = 0;
            }
            v[j].value = cValue;
          }
          this.setViewCookie(viewCookie2,JSON.stringify(v))
        }
      }
    },
    getCookieByString : function (cname,s) {
      var name = cname + "=";
      var ca = s.split(';');
      // console.log("获取cookie,现在循环")
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        // console.log(c)
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1){
          return c.substring(name.length, c.length);
        }
      }
      return "";
    }
  },
  data() {

    return {
      r1:'',
      iphoneViewCookie:  '' ,
      viewCookies1:Vue.prototype.viewCookies1,
      viewCookies2:Vue.prototype.viewCookies2,
      yesterdayCount:0,
      detailTypes:
          [{type1Name:'饮食服务', type2Names:['餐馆']},
            {type1Name:'超市', type2Names:['小超市','大超市']},
            {type1Name:'食品', type2Names:['谷物', '薯类', '豆类', '食用油和食用油脂', '蔬菜及食用菌', '畜肉类', '禽肉类', '水产品', '蛋类', '奶类', '干鲜瓜果类', '糖果糕点类', '其他食品']}
            , {type1Name:'饮料', type2Names:['可乐','雪碧','其他']}
            , {type1Name:'烟酒', type2Names:['烟草', '酒类']}
            , {type1Name:'衣类', type2Names:['服装', '服装材料', '其他衣类及配件', '衣类加工服务费']}
            , {type1Name:'鞋类', type2Names:['鞋', '鞋类配件及加工服']}
            , {type1Name:'租赁房房租', type2Names:['租赁公房房租', '租赁私房房租']}
            , {type1Name:'住房保养、维修及', type2Names:['住房装潢和维修', '物业管理费', '住房其他保养、维']}
            , {type1Name:'水、电、燃料及其', type2Names:['水', '电', '燃料', '取暖费', '其他水、电、燃料']}
            , {type1Name:'自有住房折算租金', type2Names:['用不到']}
            , {type1Name:'家具及室内装饰品', type2Names:['家具', '家具材料', '室内装饰品']}
            , {type1Name:'家用器具', type2Names:['大型家用器具', '小型家用电器', '家用电动工具和设']}
            , {type1Name:'家用纺织品', type2Names:['床上用品', '窗帘门帘', '其他家用纺织品']}
            , {type1Name:'家庭日用杂品', type2Names:['洗涤及卫生用品', '厨具、餐具、茶具', '家用手工工具', '其他家庭日用杂品']}
            , {type1Name:'个人护理用品', type2Names:['化妆品', '其他个人护理用品']}
            , {type1Name:'家庭服务', type2Names:['家政服务', '家庭设备修理']}
            , {type1Name:'交通', type2Names:['交通工具', '交通工具用燃料等', '交通工具使用和维', '交通费']}
            , {type1Name:'通信', type2Names:['通信工具', '电信服务', '邮递服务']}
            , {type1Name:'教育', type2Names:['学前教育', '小学教育', '初中教育', '高中教育', '中专职高教育', '高等教育', '其他教育和培训']}
            , {type1Name:'文化和娱乐', type2Names:['文化和娱乐耐用消', '其他文化和娱乐用', '文化和娱乐服务', '一揽子旅游度假服']}
            , {type1Name:'医疗器具及药品', type2Names:['药品', '滋补保健品', '医疗卫生器具', '保健器具']}
            , {type1Name:'医疗服务', type2Names:['门诊医疗费', '住院医疗费']}
            , {type1Name:'其他用品', type2Names:['首饰、手表', '未列明的其他用品']}
            , {type1Name:'其他服务', type2Names:['旅馆住宿', '美容、美发和洗浴', '社会保护', '保险', '金融', '未列明的其他服务']}
          ],
      showMsg :'',
      showMsgFlag:false,
      show:false,
      time:this.getYesterday(),
      showName:'显示',
      returnData:[{createDate:this.getYesterday(),user:this.getCookie("familyvuegitee_iphoneName")}],
      apps:[{count:1,id:'wx',name:'微信',ico:'https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico'},
        {count:1,id:'zfb',name:'支付宝',ico: 'https://img.alicdn.com/tfs/TB1qEwuzrj1gK0jSZFOXXc7GpXa-32-32.ico'} ,
        {count:1,id:'jd',name:'京东',ico: 'https://www.jd.com/favicon.ico'} ,
        {count:1,id:'tb',name:'淘宝',ico: 'https://img.alicdn.com/tps/i3/T1OjaVFl4dXXa.JOZB-114-114.png'} ,
        {count:1,id:'mt',name:'美团',ico: 'https://s0.meituan.net/bs/fe-web-meituan/2d53095/img/appicons/meituan.png'} ,
        {count:1,id:'ysf',name:'云闪付',ico: 'https://t9.baidu.com/it/u=4092701478,3947927877&fm=74&app=80&f=JPEG&size=f121,121?sec=1880279984&t=9cf11d0338c4535f859e9dbb07efd4f0'} ,
        {count:1,id:'zssh',name:'掌上生活',ico: 'https://t9.baidu.com/it/u=3736857898,424693942&fm=74&app=80&f=PNG&size=f121,121?sec=1880279984&t=6253b103cfe88e81a2e70a0afb77aced'} ,
        {count:1,id:'szrmb',name:'数字人民币',ico: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F1111%2F15ba6d9bj00r2eeyv000oc000hs00ieg.jpg&thumbnail=650x2147483647&quality=80&type=jpg'} ,
        {count:1,id:'xy',name:'闲鱼',ico: 'https://t8.baidu.com/it/u=3378783684,1212694708&fm=74&app=80&f=PNG&size=f121,121?sec=1880279984&t=df83528bdeea9b81260048aa86f928b2'},
        {count:1,id:'yhk',name:'银行卡',ico: 'https://img2.baidu.com/it/u=1113591676,1783871324&fm=26&fmt=auto'},
        {count:1,id:'qt',name:'其他',ico: 'https://img0.baidu.com/it/u=2856321091,8511142&fm=26&fmt=auto'} ]
    }
  },
  watch: {
    'showMsgFlag': {
      handler() {
        setTimeout(() =>{
          if (this.showMsgFlag) {
            this.showMsg = '';
            this.showMsgFlag = false;
          }
        },2000)
      },
      deep: false
    },
    // 'iphoneViewCookie':{
    //   handler(newData){
    //       console.log(newData)
    //   }
    // }

  }

}
</script>

<style scoped>

.subDetail{
  font-size: 20px;
}
.button {
  text-align: center;
  display: inline-block;
  border-radius: 4px;
  /*background-color: #f4511e;*/
  border: none;
  color: cadetblue;
  /*text-align: center;*/
  font-size: 20px;
  /*padding: 20px;*/
  width: 100px;
  height: 50px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;

  /*border: 2px solid #008CBA;*/

  -webkit-filter: opacity(87%);
  filter: opacity(87%);
}

select{
  padding: 1px 0px;
  width: 40px;
  height: 30px;
  border-radius: 2px;
}

#showRuleid{
float: right;
}
input{
  padding: 1px 0px;
  width: 80px;
  height: 30px;
  text-align: center;
}
#p5id{
  color: red;
}
#spantimeid{
  font-size: 14px;
}
</style>
